package com.pan.operation.collection;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

public class MySocketServer extends Thread {
	private ServerSocket serverSocket = null;
	private boolean listening = true;

	public MySocketServer(int port) {
		super();
		listening = true;

		try {
			serverSocket = new ServerSocket(port);
		} catch (IOException e) {
			System.err.println("Could   not   listen   on   port:   " + port);
			System.exit(-1);
		}
	}

	public void run() {
		while (listening)
			try {
				new EchoProcessThread(serverSocket.accept()).start();
			} catch (IOException e) {
				e.printStackTrace();
			}
	}

	public void stopListen() {
		listening = false;
		try {
			serverSocket.close();
		} catch (IOException e) {
		}
	}

	public static void main(String[] args) {

		int port = 1234;
		MySocketServer server = new MySocketServer(port);
		server.start();
	}
}

class EchoProcessThread extends Thread {
	private Socket socket = null;

	public EchoProcessThread(Socket socket) {
		super("EchoProcessThread");
		this.socket = socket;
	}

	public void run() {

		try {
			DataOutputStream out = new DataOutputStream(socket
					.getOutputStream());
			DataInputStream in = new DataInputStream(socket.getInputStream());

			byte oneChar = -1;
			StringBuffer sb = new StringBuffer();

			
			do{
				oneChar = in.readByte();
				//System.out.println(oneChar);
				sb.append((char)oneChar);
				//System.out.println(sb);
			}while(oneChar != -1 && oneChar != '@');
			
			
			/*
			while ((oneChar = in.readByte()) != -1 ) {
				//System.out.println((char)oneChar);
				sb.append((char)oneChar);
				System.out.println(sb);
			}*/
			
			System.out.println("content   length   " + sb.length());
			System.out.println("content   " + sb.toString());
			
			String wb = "~write   back   data@";
			out.writeBytes(wb);
			System.out.println(wb);

			out.close();
			in.close();
			socket.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
